package com.qys.livesMall.security.interceptor.core;

import com.alibaba.fastjson2.JSONObject;
import com.qys.livesMall.cache.RedisCache;
import com.qys.livesMall.cache.words.annotation.CheckWord;
import com.qys.livesMall.common.result.R;
import com.qys.livesMall.common.thread.ThreadContext;
import com.qys.livesMall.common.thread.holder.po.LoginUser;
import com.qys.livesMall.common.utils.QysStringUtils;
import com.qys.livesMall.framework.utils.SecurityUtils;
import com.qys.livesMall.security.filter.RequestWrapper;
import com.qys.livesMall.security.utils.WordUtil;
import com.qys.livesMall.user.service.ISysRoleMenuService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Set;

@Slf4j
@Order(4)
public class WordsInterceptor implements HandlerInterceptor {

    private static Log logger = LogFactory.getLog(LoginInterceptor.class);


    //handle 前

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        logger.info("***********************敏感词拦截器*************************");
        try {
            HandlerMethod hm = (HandlerMethod) handler;
            CheckWord checkWord = hm.getMethodAnnotation(CheckWord.class);
            if (checkWord == null) { //如果目标方法没有@CheckWord说明该接口不需要进行敏感词校验
                return true;
            }
        }catch (Exception e){
            log.error("敏感词拦截出错：url:{}",request.getRequestURI());
            return true;
        }
        if (request instanceof RequestWrapper) {
            RequestWrapper requestWrapper = (RequestWrapper) request;
            String body = requestWrapper.getBody();
//            log.info("处理前的请求体：{}", body);
            //替换敏感词
            body=WordUtil.filterSensitivityWord(body);
//            log.info("处理后的请求体：{}", body);
            //将处理后的body放回
            requestWrapper.setBody(body);
        }

        return true;
    }


}
